package com.jet.rtdb.socket.client.mina;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jet.rtdb.common.utils.MessageConstant;
import com.jet.rtdb.pojo.QueryHistoryDataList;
import com.jet.rtdb.pojo.QueryLastDataList;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import java.nio.ByteOrder;

/**
 * @Author: zhangkaifeng.
 * @CreateTime: 2017/8/23 11:03
 * @Description:
 */


public class RtdbProtocolEncoder extends ProtocolEncoderAdapter {
    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        if (message instanceof QueryLastDataList) {
            GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
            Gson gson = gsonbuilder.create();
            String string = gson.toJson(message);
            IoBuffer buf = IoBuffer.allocate(string.getBytes().length + 5);
            buf.order(ByteOrder.BIG_ENDIAN);
            buf.put(MessageConstant.GET_POINT_LAST_DATA);
            buf.putInt(string.getBytes().length);
            buf.put(string.getBytes());
            buf.flip();
            out.write(buf);
            out.flush();
        } else if (message instanceof QueryHistoryDataList) {
            GsonBuilder gsonbuilder = new GsonBuilder().serializeNulls();
            Gson gson = gsonbuilder.create();
            String string = gson.toJson(message);
            IoBuffer buf = IoBuffer.allocate(string.getBytes().length + 5);
            buf.order(ByteOrder.BIG_ENDIAN);
            buf.put(MessageConstant.GET_POINT_HIS_DATA);
            buf.putInt(string.getBytes().length);
            buf.put(string.getBytes());
            buf.flip();
            out.write(buf);
            out.flush();
        }
    }
}
